$(document).ready(function(){
	// Default view when load the page
//	loadTemplate('includes/account_template.php', 'account', 0);
//	connect('account');
	
	// On refresh the page
	$(window).bind('beforeunload',function(){
	});
	
	// Back and Forward Browser buttons control
	$(window).bind("popstate", function () {
//		$.getScript(location.href);
	});
	  
	
	$("#btnAccount").click(function(){
		loadTemplate('includes/account_template.php', 'account', 0);
		connect('account');
		return false;
    });
	$("#btnTransfers").click(function(){
		loadTemplate('includes/transfers_template.php', 'transfers', 0);
		connect('transfers');
		return false;
	});
	$("#btnHistory").click(function(){
		loadTemplate('includes/history_template.php', 'history', 0);
		connect("history");
		return false;
	});
	
	$("#btnLogout").click(function(){
		loadTemplate('includes/close_session.php', 'logout', 0);
		return false;
	});
	
	if(Environment.isMobile()){ 
		
	}
	
});

function connect(e){
	var info = {option:e}; // New object to POST
	$.ajax({
		url:	'includes/json_reply.php',
		type:	'POST',
		data:	info,
		dataType:'json',
		error:function(jqXHR,text_status,strError){
			// alert("no connection");
		},
		timeout:60000,
		success:function(data){
			// Printing new content
			if(e == "account"){
				$("#name").append(data.client[0]["NAME"]);
				$("#username").append(data.client[0]["USERNAME"]);
				$("#account_num").append(data.account[0]["ACCOUNT_NUM"]);
				if(data.account[0]["BALANCE"] < 0){
					$("#balance").addClass("balanceRed");
				}
				$("#balance").append(parseFloat(data.account[0]["BALANCE"]).toFixed(2) +
						" "+ data.account[0]["CURRENCY_NAME"]+
						" ("+ data.account[0]["SIMBOL"]+")");
			}
			if(e == "transfers"){
				// Set hidden input information necessary in the transfer form
				$("#trfOrigin").val(data.account[0]["ID_ACCOUNT"]);
				$("#trfCurrencyId").val(data.account[0]["CURRENCY_ID"]);
				$("#trfBalanceOr").val(data.account[0]["BALANCE"]);
				// Append data to the form
				$("#trfAccount").append(data.account[0]["ACCOUNT_NUM"]);
				$(".trfCurrency").append(" "+
						data.account[0]["CURRENCY_NAME"]+
						" ("+data.account[0]["SIMBOL"]+")");
				
				if(data.account[0]["BALANCE"] < 0){
					$("#trfBalance").addClass("balanceRed");
				}
				// Show balance with 2 decimals
				$("#trfBalance").append(parseFloat(data.account[0]["BALANCE"]).toFixed(2));
				for(var i in data.types){
					$("#trfType").append("<option value="+data.types[i]["ID_TRANSACTION_TYPE"]+">"+data.types[i]["TT_NAME"]+"</option>");
				}
				for(var i in data.destiny){
					$("#trfDestiny").append("<option value="+data.destiny[i]["ID_ACCOUNT"]+">"+data.destiny[i]["ACCOUNT_NUM"]+"</option>");
				}
			}
			if(e == "history"){
				$("#historyLoader").html("");
				var money = parseFloat(data.account[0]["BALANCE"]);
				var negativeValue = "";
				for(var i in data.history){
					// css classes setting
					var css_class = "darkblue";
					if(i % 2 == 0){ css_class = "lightblue"; }
					if(money < 0){ negativeValue="balanceRed";}else{negativeValue="";}
					// Writing the HTML and appending
					var htmlcode = "";
					htmlcode += "<tr>";
					htmlcode += "<td class='tdLong " + css_class + "'>"  + data.history[i]["ACCOUNT_ORIGIN"] + "</td>";
					htmlcode += "<td class='tdLong " + css_class + "'>"  + data.history[i]["ACCOUNT_DESTINY"] + "</td>";
					htmlcode += "<td class='tdShort " + css_class + "'>" + parseFloat(data.history[i]["AMOUNT"]).toFixed(2) + "</td>";
					htmlcode += "<td class='tdMedium " + css_class + "'>"+ data.account[0]["CURRENCY_NAME"]+" ("+data.account[0]["SIMBOL"] + ")</td>";
					htmlcode += "<td class='tdShort " + css_class + "'>" + data.history[i]["TT_NAME"] + "</td>";
					htmlcode += "<td class='tdMedium " + css_class + "'><p class="+ negativeValue +">"+ money.toFixed(2) + "</p></td>";
					htmlcode += "<td class='tdMedium " + css_class + "'>"+ data.history[i]["DATE"] + "</td>";
					htmlcode += "</tr>";

					$("#historyLoader").append(htmlcode);
					
					// Calculating next row balance
					if(data.account[0]["ACCOUNT_NUM"] == data.history[i]["ACCOUNT_ORIGIN"]){
						money = money + parseFloat(data.history[i]["AMOUNT"]);
					}else{
						money = money - parseFloat(data.history[i]["AMOUNT"]);
					}
				}
			}
		}
	});
}

function loadTemplate(url,title,option) {
	var info = "lang=" + $('html').attr('lang');
	var link = title;
	$.getScript(this.href);
	history.pushState(null, "", "index.php#"+link);
//	info = "OP="+option;
	$.ajax({
        async: false,
        cache: false,
		url: url,
		type: "GET",
		data: info,
		success: function(info){
			$("#content").html(info);
		}
	});
}

// Function for load 
function loadURL(link){
	if((link).indexOf("account") > 0){
		$( "#btnAccount" ).trigger( "click" );
	}
	if((link).indexOf("transfers") > 0){
		$( "#btnTransfers" ).trigger( "click" );
	}
	if((link).indexOf("history") > 0){
		$( "#btnHistory" ).trigger( "click" );
	}
}

var Environment = {
	    //mobile or desktop compatible event name, to be used with '.on' function
	    TOUCH_DOWN_EVENT_NAME: 'mousedown touchstart',
	    TOUCH_UP_EVENT_NAME: 'mouseup touchend',
	    TOUCH_MOVE_EVENT_NAME: 'mousemove touchmove',
	    TOUCH_DOUBLE_TAB_EVENT_NAME: 'dblclick dbltap',

	    isAndroid: function() {
	        return navigator.userAgent.match(/Android/i);
	    },
	    isBlackBerry: function() {
	        return navigator.userAgent.match(/BlackBerry/i);
	    },
	    isIOS: function() {
	        return navigator.userAgent.match(/iPhone|iPad|iPod/i);
	    },
	    isOpera: function() {
	        return navigator.userAgent.match(/Opera Mini/i);
	    },
	    isWindows: function() {
	        return navigator.userAgent.match(/IEMobile/i);
	    },
	    isMobile: function() {
	        return (Environment.isAndroid() || Environment.isBlackBerry() || Environment.isIOS() || Environment.isOpera() || Environment.isWindows());
	    }
	};